package com.nginx.web.util;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @param <T>
 * @author liyuchen
 */
@Data
public class Result<T> {

    private Integer code;
    private String msg;
    private T result;

    public static Result success() {
        return doBack(ResultEnum.SUCCESS).build();
    }

    public void put(String name, Object object) {
        if (!(result instanceof Map)) {
            result = (T) new HashMap<String, Object>(10);
        }
        Map<String, Object> r = (Map<String, Object>) result;
        r.put(name, object);
    }

    public static Result success(Object object) {
        return doBack(ResultEnum.SUCCESS).setResult(object).build();
    }

    public static Result error() {
        return doBack(ResultEnum.ERROR).build();
    }

    public static Result error(String msg) {
        return doBack(ResultEnum.ERROR).setMsg(msg).build();
    }

    public static Result doBack(ResultEnum resultEnum) {
        return new Result(resultEnum.getCode(), resultEnum.getMsg(), null);
    }

    public Result build() {
        return this;
    }

    public Result(Integer code, String msg, T result) {
        this.code = code;
        this.msg = msg;
        this.result = result;
    }

    public Result setCode(Integer code) {
        this.code = code;
        return this;
    }

    public Result setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Result setResult(T result) {
        this.result = result;
        return this;
    }

    @Override
    public String toString() {
        return "Result{" + "code=" + code + ", msg='" + msg + '\'' + ", result=" + result + '}';
    }
}
